package com.springcloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
public class IPGlobalFilter implements GlobalFilter, Ordered {

    // 初始化IP黑名单
    private static List<String> ipList = new ArrayList<>();

    static {
//        ipList.add("0:0:0:0:0:0:0:1");
        ipList.add("192.168.2.101");
    }

    /**
     * 获取客户端发送请求的ip地址，判断该ip地址是否在黑名单中，是则拒绝访问，否则放行
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取客户端IP地址
        String ip = request.getRemoteAddress().getHostString();

        // 判断ip是否在黑名单中，是则拒绝访问，否则放行
        if (ipList.contains(ip)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 封装返回对象
            String data = "拒绝访问";
            DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes());
            // 设置response响应的数据类型
            response.getHeaders().add("Content-Type", "application/json;charset=utf-8");
            // 返回响应对象
            return response.writeWith(Mono.just(dataBuffer));

        }

        return chain.filter(exchange);
    }

    /**
     * 设置filter优先级，值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 100;
    }
}
